package com.alinks.modbus.core.codec.rtu;

import com.alinks.modbus.core.codec.AbstractModbusCodec;
import com.alinks.modbus.core.exception.ModbusSlaveCodeEnum;
import com.alinks.modbus.core.frame.RtuFrame;
import com.alinks.modbus.core.frame.TcpFrame;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RtuModbusCodec extends AbstractModbusCodec<RtuFrame.Request, RtuFrame.Response> {

    @Override
    public RtuFrame.Request decode(ByteBuf in) {
        int readLength = in.readableBytes();
//        in.resetReaderIndex();
        RtuFrame.Request request = RtuFrame.Request.builder()
                .header(RtuFrame.RtuHeader.builder()
                        .unitId(in.readByte())
                        .build())
                .body(super.body(in))
                .crc(in.readShort())
                .build();
        request.setReadLength(readLength - 2);
        request.check();

        return request;
    }

    @Override
    public void encode(RtuFrame.Response response, ByteBuf out) {
        if (response.getExcept() == null) {
            out.writeBytes(response.getHeader().getHeaderBytes());
            super.body(response.getBody(), out);
            out.writeShort(response.getCrc());
        } else {
            //异常信息处理
            out.writeBytes(response.getHeader().getHeaderBytes());
            out.writeByte(response.getExcept().getFunc());
            out.writeByte(response.getExcept().getExceptCode().getCode());
        }
    }

}
